package cn.lyd.user.service.impl;

import cn.lyd.basic.exception.BusinessException;
import cn.lyd.basic.util.Md5Utils;
import cn.lyd.basic.util.StrUtils;
import cn.lyd.org.domain.Employee;
import cn.lyd.user.domain.Logininfo;
import cn.lyd.user.domain.User;
import cn.lyd.user.mapper.LogininfoMapper;
import cn.lyd.user.mapper.UserMapper;
import cn.lyd.user.service.IUserService;
import cn.lyd.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private  RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //创建Logininfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1-用户
        logininfo.setDisable(true);

        //将Logininfo对象添加到数据库，并生成自增id
        logininfoMapper.add(logininfo);//自增长id

        //将logininfo_id设置到user对象中
        user.setLogininfoId(logininfo.getId());
        //添加到数据库
        super.add(user);
        //userMapper.save(user); //效果同上
    }

    @Override
    public void del(Long id) {
        //查询user对象
        User user = userMapper.findById(id);
        //删除logininfo信息
        logininfoMapper.del(user.getLogininfoId());
        //删除user信息
        super.del(id);
    }

    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //查询到原来的user对象
        User oldUser = userMapper.findById(user.getId());
        user.setLogininfoId(oldUser.getLogininfoId());

        //更新数据t_user
        super.update(user);

        //更新数据t_logininfo
        Logininfo oldLogininfo = logininfoMapper.findById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);

        //属性同名原则会把员工的id拷贝给登录信息对象的id
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    /**
     * 手机注册
     * @param map
     */
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone =map.get("phone");
        String phoneCode =map.get("phoneCode");
        String password =map.get("password");
        String passwordRepeat =map.get("passwordRepeat");

        //1.校验空值
        if (
                StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(phoneCode)||
                StringUtils.isEmpty(password)||
                StringUtils.isEmpty(passwordRepeat)
        ) {
            throw new BusinessException("信息不能为空");
        }

        //2.校验密码是否一致
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("密码不一致");
        }

        //3.校验-手机验证码是否过期，是否正确[xxxx:213213213]   split(":")[0]-取出手机验证码
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj==null){
            throw new BusinessException("手机验证码过期");
        }
        if (!obj.toString().split(":")[0].equals(phoneCode)) {
            throw new BusinessException("手机验证码错误");
        }

        //4.添加到数据库，密码加盐加密
            User user = map2User(phone,password);
            Logininfo logininfo = user2Loginfo(user);

            //4.1.先添加t_logininfo
            logininfoMapper.add(logininfo);

            //4.2.再添加t_user
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
    }


    //将user对象的数据转成一个Logininfo对象
    private Logininfo user2Loginfo(User user) {
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id，username，phone，email，salt，password
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    //将map中的数据转成一个User对象：当一个对象转成另外一个对象的时候，并且代码量比较多
    //可以通过obj2Obj的方式单独把这个业务提取出来。提升代码的可读性。代码不臃肿
    private User map2User(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }


    /**
     * 邮箱注册
     * @param map
     */
    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email =map.get("email");
        String password =map.get("password");
        String passwordRepeat =map.get("passwordRepeat");
        //1.校验空值
        if (
                StringUtils.isEmpty(email)||
                        StringUtils.isEmpty(password)||
                        StringUtils.isEmpty(passwordRepeat)
        ) {
            throw new BusinessException("信息不能为空");
        }

        //2.校验密码是否一致
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("密码不一致");
        }

        //3.校验邮箱是否被注册过
        User euser = userMapper.findByEmail(email);
        if (euser!=null){
            throw new BusinessException("该邮箱已经注册,请直接登录。忘记密码请联系管理员!");
        }

        //4.发送激活邮件，用户点击后转到登录页面
            //1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

            //2.发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
                    true,"utf-8");

            //3.邮件内容
                //3.1发件人邮箱   setFrom
                helper.setFrom("1064751069@qq.com");

                //3.2邮件主题  setSubject
                helper.setSubject("用户激活邮件");

                //3.3邮件内容  setText
                //true - 能够再内容中编写html标签 - 会解析
                helper.setText("<h1>你的账号已经注册!!!</h1> <a href='http://127.0.0.1/login.html>点击该链接登录</a>,",true);


                //3.4收件人邮箱   setTo
                //收件人的邮箱不能写死
                helper.setTo(email);

                //4.发送邮件
                javaMailSender.send(mimeMessage);

        //5.添加到数据库，密码加盐加密
        User user = emap2User(email,password);
        Logininfo logininfo = user2Loginfo(user);

        //5.1.先添加t_logininfo
        logininfoMapper.add(logininfo);

        //5.2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);


        }

    //将map中的数据转成一个User对象：当一个对象转成另外一个对象的时候，并且代码量比较多
    //可以通过obj2Obj的方式单独把这个业务提取出来。提升代码的可读性。代码不臃肿
    private User emap2User(String email, String password) {
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }


}
